<?php
session_start();

// 配置数据库连接信息
$host = '127.0.0.1'; // 或者你的数据库地址
$dbname = 'root'; // 数据库名
$username_db = 'root'; // 数据库用户名
$password_db = '874604'; // 数据库密码


try {
    // 创建PDO实例并设置错误模式
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username_db, $password_db);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 检查是否是POST请求
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 获取POST数据并进行基本的输入验证
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['userID']) || !isset($data['password']) || !isset($data['role'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => '缺少必要参数']);
            exit;
        }

        $userID = trim($data['userID']);
        $password = trim($data['password']);
        $role = trim($data['role']);

        // 查询数据库，查找用户
        $stmt = $pdo->prepare("SELECT * FROM User WHERE UserID = :userID AND Role = :role");
        $stmt->bindParam(':userID', $userID, PDO::PARAM_INT);
        $stmt->bindParam(':role', $role, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            
            // 对于其他角色，使用password_verify验证加密后的密码
            if (password_verify($password, $user['Password'])) {
                $_SESSION['isLoggedIn'] = true;
                $_SESSION['userId'] = $user['UserID'];
                $_SESSION['username'] = $user['Username'];                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
                $_SESSION['role'] = $user['Role'];

                session_regenerate_id(true);
                setcookie(session_name(), session_id(), time() + (60 * 60 * 24 * 15), "/", "", true, true);

                http_response_code(200);
                echo json_encode(['success' => true, 'message' => '登录成功！']);
            } 
            else 
            {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => '用户名或密码错误。']);
            }
            
        } else {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => '用户名或密码错误。']);
        }
    } else {
        // 不是POST请求
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => '请通过POST方式提交数据。']);
    }
} catch (PDOException $e) {
    // 记录错误日志（生产环境中应记录到文件而不是直接输出）
    error_log("数据库错误: " . $e->getMessage());

    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '服务器内部错误，请稍后再试。']);
}
?>